//
//  AppDelegate.m
//  CustomFramework
//
//  Created by Houge on 2021/3/1.
//

#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "BaseNavigationController.h"
#import "BaseWebViewController.h"
//#import <WXApi.h>
//#import <AlipaySDK/AlipaySDK.h>
//#import "JPUSHService.h"
//#ifdef NSFoundationVersionNumber_iOS_9_x_Max
//#import <UserNotifications/UserNotifications.h>
//#endif

@interface AppDelegate ()//<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self setupRootViewController];
    [self setupThirdFrameworks];
//    [self registerJPushServiceWithOption:launchOptions];
    // 三方库没适配,现在iOS13以后不显示广告
//    [self skipToAdLaunchView];
    return YES;
}

/// 设置根控制器
- (void)setupRootViewController {
    BaseTabBarController *rootController = [[BaseTabBarController alloc] init];
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.rootViewController = rootController;
    [self.window makeKeyAndVisible];
}

/// 三方库设置
- (void)setupThirdFrameworks {
    // HUD蒙版
    [SVProgressHUD setMinimumDismissTimeInterval:2.0];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD setDefaultAnimationType:SVProgressHUDAnimationTypeNative];
    
    // 键盘管理
    IQKeyboardManager.sharedManager.enable = YES;
    
    // 微信支付
//    BOOL flag = [WXApi registerApp:WeChatAppId universalLink:WeChatUniversalLink];
//    if (!flag) {
//        NSLog(@"微信支付注册失败!");
//    } else {
//        NSLog(@"微信支付注册成功");
//    }
}


#pragma mark - AD广告页
/// 跳转到广告页
- (void)skipToAdLaunchView {
    [XHLaunchAd setLaunchSourceType:SourceTypeLaunchScreen];
    //配置广告数据
    XHLaunchImageAdConfiguration *imageAdconfiguration = [[XHLaunchImageAdConfiguration alloc] init];
    imageAdconfiguration.duration = 3;
    imageAdconfiguration.frame = self.window.bounds;
    //广告图片URLString/或本地图片名(.jpg/.gif请带上后缀)
//    imageAdconfiguration.imageNameOrURLString = @"https://gitee.com/zhunjiee/picture-bed/raw/master/iOS/ad_image.png";
    // 注：加载本地图片不要放在Assets中
    imageAdconfiguration.imageNameOrURLString = @"ad_image.png";
    //为了展示效果更好,可设置为XHLaunchAdImageCacheInBackground,先缓存,下次显示
    imageAdconfiguration.imageOption = XHLaunchAdImageCacheInBackground;
    imageAdconfiguration.contentMode = UIViewContentModeScaleToFill;
    //广告点击打开页面参数(openModel可为NSString,模型,字典等任意类型)
    imageAdconfiguration.openModel = @"http://www.baidu.com";
    imageAdconfiguration.showFinishAnimate =ShowFinishAnimateLite;
    imageAdconfiguration.showFinishAnimateTime = 0.2;
    imageAdconfiguration.skipButtonType = SkipTypeTimeText;
    //显示开屏广告
    [XHLaunchAd imageAdWithImageAdConfiguration:imageAdconfiguration delegate:self];
}

/// 广告点击事件代理方法
- (BOOL)xhLaunchAd:(XHLaunchAd *)launchAd clickAtOpenModel:(id)openModel clickPoint:(CGPoint)clickPoint {
    /** openModel即配置广告数据设置的点击广告时打开页面参数(configuration.openModel) */
    if(openModel == nil) return NO;
    
    NSString *urlString = (NSString *)openModel;
    //此处跳转页面
    BaseWebViewController *webVC = [[BaseWebViewController alloc] init];
    webVC.urlStr = urlString;
    webVC.title = @"广告";
    //此处不要直接取keyWindow
    BaseTabBarController *rootVC = (BaseTabBarController *)[[UIApplication sharedApplication].delegate window].rootViewController;
    BaseNavigationController *nav = rootVC.viewControllers.firstObject;
    [nav pushViewController:webVC animated:YES];
    return YES; //YES移除广告,NO不移除广告
}


#pragma mark - 极光推送

/// 注册极光推送
//- (void)registerJPushServiceWithOption:(NSDictionary *)launchOptions {
//    // 注册APNs通知,后台时显示
//    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
//    if (@available(iOS 12.0, *)) {
//        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;
//    } else {
//        // Fallback on earlier versions
//        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
//    }
//    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
//    [JPUSHService setupWithOption:launchOptions appKey:JPushKey channel:@"App Store" apsForProduction:YES advertisingIdentifier:nil];
//
//    // 注册自定义消息,前台时显示
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
//}
//
//- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//    /// Required - 注册 DeviceToken
//    [JPUSHService registerDeviceToken:deviceToken];
//}
//
//- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
//    //Optional
//    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
//}
//
///// 接收APNS推送通知消息
//- (void)getAPNsContent:(NSDictionary *)userInfo {
//    // 取得 APNs 标准信息内容
//    NSDictionary *aps = [userInfo valueForKey:@"aps"];
//    NSString *content = [aps valueForKey:@"alert"]; //推送显示的内容
//    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge 数量
//    NSString *sound = [aps valueForKey:@"sound"]; //播放的声音
//
//    // 取得 Extras 字段内容
//    NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服务端中 Extras 字段，key 是自己定义的
//    NSLog(@"content = [%@], badge = [%ld], sound = [%@], customize field = [%@]", content, (long)badge, sound, customizeField1);
//
//    // 设置通知红点个数
//    if (badge > 0) {
//        // 设置本地通知个数
//        [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge - 1];
//        // 修改服务器上badge的值
//        [JPUSHService setBadge:badge - 1];
//    }
//}
//
///// 接收自定义消息, APP前台显示
//- (void)networkDidReceiveMessage:(NSNotification *)notification {
//    NSDictionary * userInfo = [notification userInfo];
//    NSString *content = [userInfo valueForKey:@"content"];
//    NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
//    NSDictionary *extras = [userInfo valueForKey:@"extras"];
//    NSLog(@"messageID: %@", messageID);
//    NSLog(@"content: %@", content);
//    NSLog(@"extras: %@", extras);
//}


#pragma mark- JPUSHRegisterDelegate

/// 检测通知授权结果的回调
//- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(NSDictionary *)info {
//    if (status == JPAuthorizationStatusDenied) {
//        NSLog(@"用户关闭了通知");
//    }
//}
//
//// iOS 12 Support
//- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification {
//    NSDictionary * userInfo = notification.request.content.userInfo;
//    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        //从通知界面直接进入应用
//        [self getAPNsContent:userInfo];
//        NSLog(@"从通知界面直接进入应用");
//    } else {
//        //从通知设置界面进入应用
//        [self getAPNsContent:userInfo];
//        NSLog(@"从通知设置界面进入应用");
//    }
//}
//
//// iOS 10 Support
//- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
//    // Required
//    NSDictionary * userInfo = notification.request.content.userInfo;
//    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        [JPUSHService handleRemoteNotification:userInfo];
//        [self getAPNsContent:userInfo];
//    }
//    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有 Badge、Sound、Alert 三种类型可以选择设置
//}
//
//// iOS 10 Support
//- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
//    // Required
//    NSDictionary * userInfo = response.notification.request.content.userInfo;
//    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
//        [JPUSHService handleRemoteNotification:userInfo];
//        [self getAPNsContent:userInfo];
//    }
//    completionHandler();  // 系统要求执行这个方法
//}

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(nonnull void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
    
    if ([userActivity.activityType isEqualToString:NSUserActivityTypeBrowsingWeb]) {
        NSURL *webUrl = userActivity.webpageURL;
        if ([webUrl.host isEqualToString:@"www.vvtok.com"] || [webUrl.host isEqualToString:@"vvtok.com"]) {
            
        }
    }
    return YES;
}


#pragma mark - 支付相关

/// 如果是通过URL打开的本应用，则下面的方法会被执行
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
#pragma mark - 其他APP打开此APP
    //1.获取请求的URL地址
    NSString *urlString = [url absoluteString];
    NSLog(@"从其他应用打开此APP - urlString: %@", urlString);
    
    
#pragma mark - 支付相关
//    if ([url.scheme isEqualToString:WeChatAppId]) {
//        NSLog(@"调用微信支付");
//        //微信支付
//        return [WXApi handleOpenURL:url delegate:(id<WXApiDelegate>)self];
//
//    } else if ([url.host isEqualToString:@"safepay"]) {
//        //支付宝支付
//        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
//            [self alipayBack:resultDic];
//        }];
//    } else if ([url.scheme isEqualToString:[NSString stringWithFormat:@"tencent%@", QQAppId]]) {
//        // QQ分享
//        //        [QQApiInterface handleOpenURL:url delegate:self];
//        //        return [TencentOAuth HandleOpenURL:url];
//    }

    return YES;
}


#pragma mark - 处理微信支付回调

//- (void)onResp:(BaseResp *)resp {
//    if ([resp isKindOfClass:[PayResp class]]) { // 微信支付结果回调
//        PayResp *response = (PayResp *)resp;
//
//        NSString *result;
//        NSString *message;
//        switch (response.errCode) {
//            case WXSuccess: {
//                //支付成功
//                result = @"1";
//                message=@"支付成功";
//            }
//                break;
//            case WXErrCodeCommon:{
//                //普通错误类型
//                result = @"0";
//                message=@"支付错误";
//            }
//                break;
//            case WXErrCodeUserCancel:{
//                //用户点击取消并且返回
//                result = @"0";
//                message=@"您取消了交易";
//            }
//                break;
//            case WXErrCodeSentFail:{
//                //发送失败
//                result = @"0";
//                message=@"信息发送失败";
//            }
//                break;
//            case WXErrCodeAuthDeny:{
//                //授权失败
//                result = @"0";
//                message=@"授权失败";
//            }
//                break;
//            case WXErrCodeUnsupport:{
//                //微信不不支持
//                result = @"0";
//                message=@"您的微信版本过低";
//            }
//                break;
//            default:{
//                //位置错误
//                result = @"0";
//                message=@"支付失败";
//            }
//                break;
//        }
//
//        [[NSNotificationCenter defaultCenter] postNotificationName:APP_PAY_RESULT object:@{
//            @"result": result,
//            @"message": message
//        }];
//    }
//    else if ([resp isKindOfClass:[SendAuthResp class]]) { // 微信登录
//        if (resp.errCode == 0) {
//            //成功
//            SendAuthResp *resp2 = (SendAuthResp *)resp;
//            NSLog(@"=============- (void)onResp:(BaseResp *)resp=========");
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"wechatLoginNOTFI" object:resp2];
//        } else {
//            [SVProgressHUD showMessage:@"微信授权失败"];
//        }
//    }
//    else if ([resp isKindOfClass:[SendMessageToWXResp class]]) {  // 微信分享结果
//        NSString *result;
//        NSString *message;
//        if (resp.errCode == 0) {
//            result = @"1";
//            message=@"分享成功";
//        } else {
//            result = @"0";
//            message=@"分享失败";
//        }
//        [[NSNotificationCenter defaultCenter] postNotificationName:APP_SHARE_RESULT object:@{
//            @"result": result,
//            @"message": message
//        }];
//    }
//}


#pragma mark 处理支付宝支付回调

//- (void)alipayBack:(NSDictionary *)resultDic {
//
//    NSLog(@"alipayBack --- %@", resultDic);
//
//    NSString *memo;
//    NSString *result;
//    NSString *resultStatus;
//    NSString *resultCode;
//    NSString *message;
//
//    memo = resultDic[@"memo"];
//    result = resultDic[@"result"];
//    resultStatus = resultDic[@"resultStatus"];
//
//    if ([resultStatus isEqualToString:@"9000"]) {
//        //支付成功
//        resultCode = @"1";
//        message = @"支付成功";
//
//    } else if ([resultStatus isEqualToString:@"8000"]) {
//        //正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
//        resultCode = @"0";
//        message = @"正在处理...";
//
//    } else if ([resultStatus isEqualToString:@"4000"]) {
//        //订单支付失败
//        resultCode = @"0";
//        message = @"订单支付失败";
//
//    } else if ([resultStatus isEqualToString:@"5000"]) {
//        //重复请求
//        resultCode = @"0";
//        message = @"您的订单已经提交，请勿重复操作";
//
//    } else if ([resultStatus isEqualToString:@"6001"]) {
//        //用户中途取消
//        resultCode = @"0";
//        message = @"您已取消支付";
//
//    } else if ([resultStatus isEqualToString:@"6002"]) {
//        //网络连接出错
//        resultCode = @"0";
//        message = @"网络连接出错";
//
//    } else if ([resultStatus isEqualToString:@"6004"]) {
//        //支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
//        resultCode = @"0";
//        message = @"订单出现异常，请在订单列表中查看支付状态";
//
//    } else {
//        //其它支付错误
//        resultCode = @"0";
//        message = @"支付失败";
//
//    }
//
//    [[NSNotificationCenter defaultCenter] postNotificationName:APP_PAY_RESULT object:@{
//        @"result": resultCode,
//        @"message": message
//    }];
//}


#pragma mark - UISceneSession lifecycle


- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options  API_AVAILABLE(ios(13.0)){
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}


- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions  API_AVAILABLE(ios(13.0)){
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}


@end
